/*
 * 角色验证守卫，用于验证用户角色
 */

import {
  Injectable,
  CanActivate,
  ExecutionContext,
  HttpStatus,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { CustomExceptionFilter } from '@/core/filters';

@Injectable()
export class RoleGuard implements CanActivate {
  constructor(private reflector: Reflector) {}
  // context 请求的(Response/Request)的引用
  canActivate(context: ExecutionContext): boolean {
    // 从元数据中获取角色信息
    const requiredRoles = this.reflector.get<string[]>(
      'roles',
      context.getHandler(),
    );

    // 如果没有设置角色要求,则允许访问
    if (requiredRoles?.length === 0) {
      return true;
    }

    const request = context
      .switchToHttp()
      .getRequest<Request & { user: { role: string } }>();
    const user = request.user;
    if (!user)
      throw new CustomExceptionFilter(
        '用户角色不存在',
        HttpStatus.UNAUTHORIZED,
      );

    const hasRole = requiredRoles.some((role) => user.role === role);
    return hasRole;
  }
}
